{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Main where
import Miso
import Miso.String
import qualified App.Article.Controller as AAC
import Lib.View.Tabs
import Lib.View.Stack
import AppEvent
import AppModel
import App.Article.View
import App.Article.Event
import qualified Data.Map as M
import qualified Data.List as L
import  Control.Monad.ST
import Data.STRef

main :: IO ()
main = do
  startApp App {..}
  where
    initialAction = DoSelectIdx 0
    model  = ViewModel ["Tabs"] 0 (ArticleModel [] Nothing)
    update = updateModel
    view   = renderView
    events = defaultEvents
    subs   = []
    mountPoint = Nothing

tabViewModel = TabViewModel {
   tabWrapper = (div_ [class_ "app_footer"])
  ,itemLst  = [tabItem "文章" "book",tabItem "想法" "lightbulb-o",tabItem "用户" "user",tabItem "设置" "gear"]
  ,ctxList = [viewArticle,stView,viewArticle,viewArticle]
  ,rootWrapper = (div_ [class_ "app_root"])
  ,ctxModel = [articleModel,articleModel,articleModel,articleModel]
}

renderView::ViewModel -> View Action
renderView vm@ViewModel{..} =  stackView viewStack stackMap
  where
    tabV = tabView vm selectIdx tabViewModel
    stackMap::M.Map String (View Action)
    stackMap = M.fromList [("Tabs",tabV),("PageDetail",renderArticlePage articleModel)]


updateModel :: Action -> ViewModel -> Effect Action ViewModel
updateModel (DoSelectIdx 0) m = m {selectIdx = 0} <# AAC.enterArticle
updateModel (DoSelectIdx 1) m = m {selectIdx = 1} <# noOP
updateModel (DoSelectIdx 2) m = m {selectIdx = 2} <# noOP
updateModel (DoSelectIdx 3) m = m {selectIdx = 3} <# noOP
updateModel (DoSelectIdx idx) m = noEff m {selectIdx = idx}
--updateModel (ArticleEv (OpenDetailArticle openIdx)) m = noEff $ m {viewStack = ("PageDetail":(viewStack m))}
updateModel BackEvent m = noEff $ m {viewStack = L.tail (viewStack m)}
updateModel (ArticleEv aEV) m =  AAC.controllerArticle aEV m
updateModel _ m = noEff m

noOP = do
  pure NoOp

tabItem::MisoString -> MisoString -> Int -> Bool -> View Action
tabItem nameText classText idx isSel  = div_ [classList_ [("item_root",True),("item_sel",isSel)],onClick $ DoSelectIdx idx] [
  i_ [class_ ("fa fa-lg fa-" <> classText)] [],
  div_ [class_ "icon_text"] [text nameText]
 ]

stView::ArticleModel -> View Action
stView am = setST
 where
  setST = runST $ do
    d <- newSTRef "666"
    rd <- readSTRef d
    return $ innerView rd
  innerView str = 
    div_ [] [text str]
